import React, { useState } from 'react';
import styles from './index.less';
import {
  Modal,
  Space,
  DatePicker,
  Button,
  Input,
  Table,
  Form,
  Select,
  message,
  Spin,
} from 'antd';
const { RangePicker } = DatePicker;
import { CEdit, CourseEditObject } from '@/pages/admin/course/cEdit';
import { getCourse } from '@/pages/admin/pulic';
import {
  ChooseStudent,
  CStudentEditObject,
} from '@/pages/admin/course/chooseStudent';
import request from '@/http';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import qs from 'qs';

const { confirm } = Modal;

const { Option } = Select;

export default () => {
  const [chooseStudentObject, setChooseStudentObject] =
    React.useState<CStudentEditObject>({
      isModalVisible: false,
    });
  const [cEditObject, setCEditObject] = React.useState<CourseEditObject>({
    isModalVisible: false,
  });

  const [formObject] = Form.useForm();
  const [searchValue, setSearchValue] = React.useState('');
  const [dataSource, setDataSource] = React.useState<any[]>([]);
  const [loadingState, setLoadingState] = React.useState({ loading: true });
  const [pagination, setPagination] = React.useState({
    current: 1,
    total: 10,
    pageSize: 10,
    showSizeChanger: true,
    pageSizeOptions: ['10', '50', '200', '500'],
    showQuickJumper: true,
  });

  const loadDataSource = async (
    userParams: any,
    pageValue: any,
    pageSize: any,
  ) => {
    const ds = {
      ...userParams,
      currentPage: pageValue ? pageValue : 1,
      size: pageSize ? pageSize : 5,
    };

    const result: any = await request.post(
      '/api/admin/course/TermSelCourse',
      qs.stringify(ds),
    );

    if (result.code === 200) {
      const arr: string | any[] = [];
      const data = result.data.data.map((user: any) => ({
        key: `user_${user.id}`,
        id: user.id,
        courseName: user.courseName, //	课程名（项目名称）
        projectDate: user.projectDate, //
        trainTeacher: user.trainTeacher,
        dutyTeacher: user.dutyTeacher,
        signInTime: user.signInTime,
        signOutTime: user.signOutTime,
        classRome: user.classRome,
        remark: user.remark,
      }));

      const newPageObject = {
        ...pagination,
        current: pageValue,
        pageSize: pageSize,
        total: result.records, //总条数 分页               *******************
      };

      setPagination(newPageObject);
      setDataSource(data);
      setLoadingState({ loading: false });
    }
  };

  //搜索 项目名称  查询老师下的课程
  let cCourse = localStorage.getItem('course');
  if (cCourse != null) {
    var cCourseData = JSON.parse(cCourse);
  }

  let cTeacher = localStorage.getItem('teacher');
  if (cTeacher != null) {
    var cTeacherData = JSON.parse(cTeacher);
  }

  const searchOnClick = async () => {
    setLoadingState({ loading: true });
    const data = formObject.getFieldsValue();
    console.log(data);
    var ds = {
      ...data,
      startDate: data.projectDate
        ? data.projectDate[0].format('yyyy-MM-DD')
        : '',
      endDate: data.projectDate ? data.projectDate[1].format('yyyy-MM-DD') : '',
      dutyTeacher: data.dutyTeacherName,
    };
    await loadDataSource(ds, 1, pagination.pageSize);
  };

  React.useEffect(() => {
    loadDataSource(null, 1, pagination.pageSize).finally();
    getCourse();
    // getTrainTeacher()
  }, []);

  const pageOnChange = async (page: any) => {
    await loadDataSource(
      formObject.getFieldsValue(),
      page.current,
      page.pageSize,
    );
  };

  async function userEditOnClose() {
    await loadDataSource(
      formObject.getFieldsValue(),
      pagination.current,
      pagination.pageSize,
    );
  }
  const deleteOnClick = async (user: any) => {
    const result: any = await request.post(
      '/api/admin/course/DeleteCourse',
      qs.stringify({
        courseOnId: user.id,
      }),
    );
    console.log(user);
    if (result.code == 200) {
      setTimeout(() => {
        message.success('操作成功！');
      }, 200);
      await loadDataSource(
        formObject.getFieldsValue(),
        pagination.current,
        pagination.pageSize,
      );
    } else {
      setTimeout(() => {
        message.success(result.message);
      }, 200);
    }
  };

  const resetOnClick = () => {
    formObject.resetFields();
    loadDataSource(1, 1, pagination.pageSize);
  };

  function showDeleteConfirm(val: any) {
    confirm({
      icon: <ExclamationCircleOutlined />,
      title: '温馨提示',
      content: '是否删除该课程？',
      okText: '确认',
      okType: 'danger',
      cancelText: '取消',
      onOk() {
        deleteOnClick(val).then((r) => {
          console.log('ok');
        });
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  }

  return (
    <div className="pageMain">
      <div className="pageContent">
        <div className={styles.searchForm} style={{ width: 1500 }}>
          <Form layout="inline" form={formObject}>
            <Form.Item label="日期" name="projectDate">
              <RangePicker format="YYYY-MM-DD" />
              {/*<DatePicker showTime style={{ width: 220 }} format="YYYY-MM-DD" />*/}
            </Form.Item>

            <Form.Item label="项目名称" name="courseName" initialValue="">
              <Select className="courseSelect">
                <Option value="">请选择...</Option>
                {cCourseData
                  ? cCourseData.map((item: any, index: any) => {
                      return (
                        <Option
                          index={index}
                          key={index}
                          value={item.courseName}
                        >
                          {item.courseName}
                        </Option>
                      );
                    })
                  : ''}
              </Select>
            </Form.Item>
            <Form.Item label="实训老师" name="trainTeacher" initialValue="">
              <Select className="courseSelect">
                <Option value="">请选择...</Option>
                {cTeacherData
                  ? cTeacherData.map((item: any, index: any) => {
                      return (
                        <Option
                          index={index}
                          key={index}
                          value={item.teacherName}
                          children={item.teacherName}
                        />
                      );
                    })
                  : ''}
              </Select>
            </Form.Item>
            <Form.Item label="责任老师" name="dutyTeacherName" initialValue="">
              <Select className="courseSelect">
                <Option value="">请选择...</Option>
                {cTeacherData
                  ? cTeacherData.map((item: any, index: any) => {
                      return (
                        <Option
                          index={index}
                          key={index}
                          value={item.teacherName}
                          children={item.teacherName}
                        />
                      );
                    })
                  : ''}
              </Select>
            </Form.Item>

            <Form.Item>
              <Button onClick={searchOnClick} type="primary">
                查询
              </Button>
              <Button onClick={resetOnClick} style={{ marginLeft: 20 }}>
                重置
              </Button>
            </Form.Item>
          </Form>
        </div>
        <div className={styles.mainTable}>
          <Button
            style={{ marginBottom: '10px' }}
            type="primary"
            onClick={() => {
              setCEditObject({
                isModalVisible: true,
              });
            }}
          >
            新增
          </Button>
          <Spin tip="Loading..." spinning={loadingState.loading}>
            <Table
              columns={[
                {
                  title: '日期',
                  dataIndex: 'projectDate',
                  key: 'projectDate',
                  width: 75,
                  align: 'center',
                },
                {
                  title: '项目名称',
                  dataIndex: 'courseName',
                  key: 'courseName',
                  width: 100,
                  align: 'center',
                },
                {
                  title: '实训老师',
                  dataIndex: 'trainTeacher',
                  key: 'trainTeacher',
                  width: 100,
                  align: 'center',
                },
                {
                  title: '责任老师',
                  dataIndex: 'dutyTeacher',
                  key: 'dutyTeacher',
                  width: 75,
                  align: 'center',
                },
                {
                  title: '签到时间',
                  dataIndex: 'signInTime',
                  key: 'signInTime',
                  width: 100,
                  align: 'center',
                },
                {
                  title: '签退时间',
                  dataIndex: 'signOutTime',
                  key: 'signOutTime',
                  width: 100,
                  align: 'center',
                },
                {
                  title: '教室',
                  dataIndex: 'classRome',
                  key: 'classRome',
                  width: 75,
                  align: 'center',
                },
                {
                  title: '备注',
                  dataIndex: 'remark',
                  key: 'remark',
                  width: 100,
                  align: 'center',
                },

                {
                  title: '操作',
                  key: 'action',
                  align: 'center',
                  width: 125,
                  render: (row: any) => (
                    <>
                      <Button
                        type="link"
                        onClick={() => {
                          setChooseStudentObject({
                            ...row,
                            isModalVisible: true,
                          });
                        }}
                        style={{ padding: '4px 5px' }}
                      >
                        选择学生
                      </Button>
                      <Button
                        type="link"
                        onClick={() => {
                          setCEditObject({
                            ...row,
                            isModalVisible: true,
                          });
                        }}
                        style={{ padding: '4px 5px' }}
                      >
                        编辑
                      </Button>
                      <Button
                        type="link"
                        onClick={() => {
                          showDeleteConfirm({
                            ...row,
                          });
                        }}
                        style={{ padding: '4px 5px' }}
                      >
                        删除
                      </Button>
                      <Button type="link" style={{ padding: '4px 5px' }}>
                        复制
                      </Button>
                    </>
                  ),
                },
              ]}
              dataSource={dataSource}
              pagination={pagination}
              onChange={pageOnChange}
              tableLayout="fixed"
              bordered
            />
          </Spin>
        </div>
        <ChooseStudent editObject={chooseStudentObject} />
        <CEdit editObject={cEditObject} />
      </div>
    </div>
  );
};
